package com.qifan.energy.http.response;

import com.alibaba.fastjson.JSON;
import com.qifan.energy.activity.SignInActivity;
import com.qifan.energy.bean.result.LoginResult;
import com.qifan.energy.global.Keys;
import com.qifan.energy.util.ActivityStackUtil;
import com.qifan.energy.util.GsonUtils;
import com.qifan.energy.util.IntentUtils;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.util.UIUtils;
import com.qifan.energy.widget.dialog.LoadingUtils;
import com.qifan.energy.http.net.NetUtils;
import com.orhanobut.logger.Logger;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 数据返回统一处理  参考https://www.jianshu.com/p/ff619fea7e22
 * @param <T>
 */
public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {

    private static final String TAG = "BaseObserver";

    @Override
    public void onNext(BaseResponse<T> response) {
        //在这边对 基础数据 进行统一处理  举个例子：
        if(response.getCode()==200 || response.getCode()==0){
            T data = response.getData();
            if (data != null){
                ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
                Type actualTypeArgument = pt.getActualTypeArguments()[0];
                if (data.getClass() == actualTypeArgument){
                    onSuccess(data);
                } else {
                    String jsonString = JSON.toJSONString(data);
                    T t = GsonUtils.getGson().fromJson(jsonString, actualTypeArgument);
                    onSuccess(t);
                }
            } else {
                onSuccess(null);
            }
        } else if(response.getCode()==401) {
            //隐藏弹窗
            LoadingUtils.hide();
            //删除token
            NetUtils.removeToken();
            //从本地删除用户信息
            SharedPreferencesUtil.putData(Keys.TOKEN_KEY,"");
            //提示
            ToastUtils.showShort("为了您的账号安全，请重新登录");
            //token失效，强制退出
            ActivityStackUtil.finishAllActivity();
            IntentUtils.startActivityWithFlag(UIUtils.getContext(), SignInActivity.class);
        } else{
            if (response.getData() instanceof String){
                onFailure(null,(String)response.getData());
            } else {
                onFailure(null,response.getMessage());
            }
        }
    }

    @Override
    public void onError(Throwable e) {//服务器错误信息处理
        onFailure(e, RxExceptionUtil.exceptionHandler(e));
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    /* 刷新获取新token */
    private void refreshToken(){
        NetUtils.refreshToken(new MyObserver<LoginResult>(UIUtils.getContext()) {
            @Override
            public void onSuccess(LoginResult result) {
                //提示并跳转页面
                ToastUtils.showShort("刷新Token成功!");
                //保存Token
                Logger.i("token->authorization->:",result.getToken());
                NetUtils.saveToken(result.getToken());
                SharedPreferencesUtil.putData(Keys.TOKEN_KEY,result.getToken());
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    public abstract void onSuccess(T result);

    public abstract void onFailure(Throwable e, String errorMsg);
}
